    //
//  NetworkManager.m
//  KIASupervisory
//
//  Created by tan_xin on 14-7-9.
//  Copyright (c) 2014年 MyCompany. All rights reserved.
//

#import "NetworkManager.h"
#import "JSON.h"
#import "NSString+HNSURLEncodedAdditions.h"

@interface NetworkManager ()

@property (nonatomic, assign, readwrite) RequestMethodId methodId;
@property (nonatomic, strong) ASIHTTPRequest *httpRequest;
@property (nonatomic, strong) ASIFormDataRequest *httpPostRequest;
@property (nonatomic, strong) NSCondition *lock;

@end

@implementation NetworkManager


// 判断是不是有网络
+(BOOL)connectedToNetwork {
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;
    
    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    
    if (!didRetrieveFlags) {
        return NO;
    }
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    
    return (isReachable && !needsConnection) ? YES : NO;
}

- (id)init {
    self = [super init];
    if (self) {
        _isCancelled = NO;
        _requestDict = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (NSString *)getParamStringByParamDict:(NSDictionary *)param {
    NSString *strParam = @"";
    NSArray *allKeys = [param allKeys];
    if ([allKeys count] > 0) {
        for (NSString *key in allKeys) {
            NSString *value = [param objectForKey:key];
            value = [value urlEncodedFormStringUsingEncoding:NSUTF8StringEncoding];
            strParam = [strParam stringByAppendingFormat:@"&%@=%@",key,value];
        }
    }
    return strParam;
}

- (BOOL)requestWithMethod:(RequestMethodId)method parameter:(id)param delegate:(id)delegate {
    [_lock lock];
    
    self.delegate = delegate;
    self.methodId = method;
    
    NSString *methodName = [Constants getRequestMethodNameByID:method];
    
    BOOL isPostMethod = YES;
    
    ASIHTTPRequest *request = nil;
    
    if (isPostMethod) { //post方法
        NSString *strURL = [NSString stringWithFormat:@"%@",SERVER_DOMAIN];
        //DebugLog(@"******method:%@,url:%@",methodName,strURL);
        //NSLog(@"******method:%@,url:%@",methodName,strURL);
//        if (method == createWeixiu) {
//            methodName=@"";
//            strURL=@"http://192.168.1.100:8080/zhihuiguanjia/mobile/export.shtml";
//        }
        NSLog(@"******method:%@,url:%@",methodName,strURL);

        //strURL=@"http://127.0.0.1:8080/ufu/mobile/mobileRequest.shtml";
        NSURL *url = [NSURL URLWithString:strURL];
        
        self.httpPostRequest = [ASIFormDataRequest requestWithURL:url];
        self.httpPostRequest.tag = method;
        self.httpPostRequest.timeOutSeconds = 20;
        
        request = (ASIHTTPRequest *)_httpPostRequest;
        
        [self.httpPostRequest addPostValue:methodName forKey:@"method"];
        
        NSArray *keys = [param allKeys];
        NSLog(@"******post param:%@",param);
        if ([keys count] > 0) {
            for (NSString *key in keys) {
                id value = [param objectForKeyOrNil:key];
                
                if ([key isEqualToString:@"FILE"]) { //上传文件

                    NSArray *files = (NSArray *)value;
                    for (NSDictionary *dict in files) {
                        NSString *fileName = [dict objectForKeyOrNil:@"name"];
                        NSData *fileData = [dict objectForKeyOrNil:@"path"];
                        
                        NSString *strKey = @"";
                        NSArray *nameArr = [fileName componentsSeparatedByString:@"."];
                        if ([nameArr count] > 0) {
                            NSString *name = [nameArr objectAtIndex:0];
                            strKey = [NSString stringWithFormat:@"input_path%@",name];
                        }
                        NSLog(@"*******filename:%@,key:%@",fileName,strKey);
                        
                        [self.httpPostRequest addData:fileData
                                         withFileName:fileName
                                       andContentType:@"application/octet-stream"
                                               forKey:strKey];
                    }

                } else { //普通参数
                    if (value != nil) {
                        NSString *strKey = [NSString stringWithFormat:@"%@",key];
                        NSLog(@"*****key:%@,value:%@",strKey,value);
                        [self.httpPostRequest addPostValue:value forKey:strKey];
                    }
                }
            }
        }
        
        self.isCancelled = NO;
        
    } else { //get方法
        NSString *paramStr = @"{\'pwd\':\'123456\',\'username\':\'admin@qq.com\'}";
        NSString *strURL = [NSString stringWithFormat:@"%@?method=%@&params=%@",SERVER_DOMAIN,methodName,paramStr];
        NSLog(@"******method:%@,url:%@",methodName,strURL);
        NSURL *url = [NSURL URLWithString:strURL];
        
        self.httpRequest = [ASIHTTPRequest requestWithURL:url];
        self.httpRequest.tag = method;
        self.httpRequest.timeOutSeconds = 20;
        
        request = self.httpRequest;
        
        self.isCancelled = NO;
    }
    
    [request setCompletionBlock:^{
        NSData *data = [request responseData];
        NSStringEncoding gbkEncoding =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
//        NSString *responseString = [[NSString alloc] initWithData:data encoding:gbkEncoding];
        NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        
//        DebugLog(@"******completion responseString:%@",responseString);
        
        if ([responseString length] > 0) {
            SBJSON *json= [[SBJSON alloc] init];
            NSDictionary *responseDict = [json objectWithString:responseString error:nil];
//            DebugLog(@"*******result:%@",responseDict);
            
            NSString *errorNo = [responseDict objectForKey:@"code"];
            NSString *errorMsg = [responseDict objectForKey:@"msg"];
            
//            DebugLog(@"*******request tag:%d",request.tag);
            if ([errorNo integerValue] == 0) { //请求成功
                if ((_delegate != nil) &&
                    [_delegate respondsToSelector:@selector(network:methodId:didRequestFinishedWithResult:)] &&
                    !self.isCancelled) {
                    [_delegate network:self methodId:request.tag didRequestFinishedWithResult:responseDict];
                }
            } else {
                NSDictionary *errorInfo = [NSDictionary dictionaryWithObjectsAndKeys:errorMsg,@"errorMsg", nil];
                NSError *error = [NSError errorWithDomain:@"KIASupervisory" code:[errorNo integerValue] userInfo:errorInfo];
                if ((_delegate != nil) &&
                    [_delegate respondsToSelector:@selector(network:methodId:didRequestFailedWithError:)] &&
                    !self.isCancelled) {
                    
                    [_delegate network:self methodId:request.tag didRequestFailedWithError:error];
                }
            }
        } else {
            NSDictionary *errorInfo = [NSDictionary dictionaryWithObjectsAndKeys:@"请求失败11",@"errorMsg", nil];
            NSError *error = [NSError errorWithDomain:@"KIASupervisory" code:-1 userInfo:errorInfo];
            if ((_delegate != nil) &&
                [_delegate respondsToSelector:@selector(network:methodId:didRequestFailedWithError:)] &&
                !self.isCancelled) {
                
                [_delegate network:self methodId:request.tag didRequestFailedWithError:error];
            }
        }
        
    }];
    
    [request setFailedBlock:^{
        NSData *data = [request responseData];
        NSStringEncoding gbkEncoding =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
        NSString *responseString = [[NSString alloc] initWithData:data encoding:gbkEncoding];
//        NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        
//        DebugLog(@"******failed responseString:%@",responseString);
        
        if (request.error.domain == NSURLErrorDomain) {
            NSString *errorMsg = [request.error.userInfo objectForKey:@"NSLocalizedDescription"];
            if (!errorMsg || [errorMsg length]==0) {
                errorMsg = @"您的网络不給￼力哦！";
            }
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                            message:errorMsg
                                                           delegate:nil
                                                  cancelButtonTitle:@"取消"
                                                  otherButtonTitles:nil];
            [alert show];
        } else {
            NSDictionary *errorInfo = [NSDictionary dictionaryWithObjectsAndKeys:@"请求失败",@"errorMsg", nil];
            NSError *error = [NSError errorWithDomain:@"KIASupervisory" code:-1 userInfo:errorInfo];
            if (_delegate &&
                [_delegate respondsToSelector:@selector(network:methodId:didRequestFailedWithError:)] &&
                !self.isCancelled) {
                
                [_delegate network:self methodId:self.methodId didRequestFailedWithError:error];
            }
        }
    }];
    
    [request startAsynchronous];
    
    return YES;
    
    [_lock unlock];
    return NO;
}

- (BOOL)requestWithMethod2:(RequestMethodId)method parameter:(id)param delegate:(id)delegate {
    [_lock lock];
    
    self.delegate = delegate;
    self.methodId = method;
    
    NSString *methodName = [Constants getRequestMethodNameByID:method];
    
    BOOL isPostMethod = YES;
    
    ASIHTTPRequest *request = nil;
    
    if (isPostMethod) { //post方法
        NSString *strURL = [NSString stringWithFormat:@"%@",SERVER_DOMAIN2];
        //DebugLog(@"******method:%@,url:%@",methodName,strURL);
        //NSLog(@"******method:%@,url:%@",methodName,strURL);
        //        if (method == createWeixiu) {
        //            methodName=@"";
        //            strURL=@"http://192.168.1.100:8080/zhihuiguanjia/mobile/export.shtml";
        //        }
        NSLog(@"******method:%@,url:%@",methodName,strURL);
        
        //strURL=@"http://127.0.0.1:8080/ufu/mobile/mobileRequest.shtml";
        NSURL *url = [NSURL URLWithString:strURL];
        
        self.httpPostRequest = [ASIFormDataRequest requestWithURL:url];
        self.httpPostRequest.tag = method;
        self.httpPostRequest.timeOutSeconds = 20;
        
        request = (ASIHTTPRequest *)_httpPostRequest;
        
        [self.httpPostRequest addPostValue:methodName forKey:@"method"];
        
        NSArray *keys = [param allKeys];
        NSLog(@"******post param:%@",param);
        if ([keys count] > 0) {
            for (NSString *key in keys) {
                id value = [param objectForKeyOrNil:key];
                
                if ([key isEqualToString:@"FILE"]) { //上传文件
                    
                    NSArray *files = (NSArray *)value;
                    for (NSDictionary *dict in files) {
                        NSString *fileName = [dict objectForKeyOrNil:@"name"];
                        NSData *fileData = [dict objectForKeyOrNil:@"path"];
                        
                        NSString *strKey = @"";
                        NSArray *nameArr = [fileName componentsSeparatedByString:@"."];
                        if ([nameArr count] > 0) {
                            NSString *name = [nameArr objectAtIndex:0];
                            strKey = [NSString stringWithFormat:@"input_path%@",name];
                        }
                        NSLog(@"*******filename:%@,key:%@",fileName,strKey);
                        
                        [self.httpPostRequest addData:fileData
                                         withFileName:fileName
                                       andContentType:@"application/octet-stream"
                                               forKey:strKey];
                    }
                    
                } else { //普通参数
                    if (value != nil) {
                        NSString *strKey = [NSString stringWithFormat:@"%@",key];
                        NSLog(@"*****key:%@,value:%@",strKey,value);
                        [self.httpPostRequest addPostValue:value forKey:strKey];
                    }
                }
            }
        }
        
        self.isCancelled = NO;
        
    } else { //get方法
        NSString *paramStr = @"{\'pwd\':\'123456\',\'username\':\'admin@qq.com\'}";
        NSString *strURL = [NSString stringWithFormat:@"%@?method=%@&params=%@",SERVER_DOMAIN,methodName,paramStr];
        NSLog(@"******method:%@,url:%@",methodName,strURL);
        NSURL *url = [NSURL URLWithString:strURL];
        
        self.httpRequest = [ASIHTTPRequest requestWithURL:url];
        self.httpRequest.tag = method;
        self.httpRequest.timeOutSeconds = 20;
        
        request = self.httpRequest;
        
        self.isCancelled = NO;
    }
    
    [request setCompletionBlock:^{
        NSData *data = [request responseData];
        NSStringEncoding gbkEncoding =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
        //        NSString *responseString = [[NSString alloc] initWithData:data encoding:gbkEncoding];
        NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        
        //        DebugLog(@"******completion responseString:%@",responseString);
        
        if ([responseString length] > 0) {
            SBJSON *json= [[SBJSON alloc] init];
            NSDictionary *responseDict = [json objectWithString:responseString error:nil];
            //            DebugLog(@"*******result:%@",responseDict);
            
            NSString *errorNo = [responseDict objectForKey:@"code"];
            NSString *errorMsg = [responseDict objectForKey:@"msg"];
            
            //            DebugLog(@"*******request tag:%d",request.tag);
            if ([errorNo integerValue] == 0) { //请求成功
                if ((_delegate != nil) &&
                    [_delegate respondsToSelector:@selector(network:methodId:didRequestFinishedWithResult:)] &&
                    !self.isCancelled) {
                    [_delegate network:self methodId:request.tag didRequestFinishedWithResult:responseDict];
                }
            } else {
                NSDictionary *errorInfo = [NSDictionary dictionaryWithObjectsAndKeys:errorMsg,@"errorMsg", nil];
                NSError *error = [NSError errorWithDomain:@"KIASupervisory" code:[errorNo integerValue] userInfo:errorInfo];
                if ((_delegate != nil) &&
                    [_delegate respondsToSelector:@selector(network:methodId:didRequestFailedWithError:)] &&
                    !self.isCancelled) {
                    
                    [_delegate network:self methodId:request.tag didRequestFailedWithError:error];
                }
            }
        } else {
            NSDictionary *errorInfo = [NSDictionary dictionaryWithObjectsAndKeys:@"请求失败11",@"errorMsg", nil];
            NSError *error = [NSError errorWithDomain:@"KIASupervisory" code:-1 userInfo:errorInfo];
            if ((_delegate != nil) &&
                [_delegate respondsToSelector:@selector(network:methodId:didRequestFailedWithError:)] &&
                !self.isCancelled) {
                
                [_delegate network:self methodId:request.tag didRequestFailedWithError:error];
            }
        }
        
    }];
    
    [request setFailedBlock:^{
        NSData *data = [request responseData];
        NSStringEncoding gbkEncoding =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
        NSString *responseString = [[NSString alloc] initWithData:data encoding:gbkEncoding];
        //        NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        
        //        DebugLog(@"******failed responseString:%@",responseString);
        
        if (request.error.domain == NSURLErrorDomain) {
            NSString *errorMsg = [request.error.userInfo objectForKey:@"NSLocalizedDescription"];
            if (!errorMsg || [errorMsg length]==0) {
                errorMsg = @"您的网络不給￼力哦！";
            }
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                            message:errorMsg
                                                           delegate:nil
                                                  cancelButtonTitle:@"取消"
                                                  otherButtonTitles:nil];
            [alert show];
        } else {
            NSDictionary *errorInfo = [NSDictionary dictionaryWithObjectsAndKeys:@"请求失败",@"errorMsg", nil];
            NSError *error = [NSError errorWithDomain:@"KIASupervisory" code:-1 userInfo:errorInfo];
            if (_delegate &&
                [_delegate respondsToSelector:@selector(network:methodId:didRequestFailedWithError:)] &&
                !self.isCancelled) {
                
                [_delegate network:self methodId:self.methodId didRequestFailedWithError:error];
            }
        }
    }];
    
    [request startAsynchronous];
    
    return YES;
    
    [_lock unlock];
    return NO;
}



#pragma mark - success
- (void)requestFinished:(ASIHTTPRequest *)request {
    NSData *data = [request responseData];
    NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    DebugLog(@"******requestFinished result:%@",responseString);
    
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    NSData *data = [request responseData];
    NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    DebugLog(@"******requestFailed result:%@",responseString);
    
}


@end
